<template>
  <div class="map-container">
    <!-- 地图容器 -->
    <div id="mapDiv" class="map"></div>

    <!-- 右键菜单弹出表单 -->
    <el-dialog v-model="dialogVisible" title="填写军事事件" width="600px">
      <el-form :model="militaryEvent" label-width="100px">
        <el-form-item label="事件名称">
          <el-input v-model="militaryEvent.eventName" />
        </el-form-item>

        <el-form-item label="事件描述">
          <el-input v-model="militaryEvent.eventDescription" type="textarea" />
        </el-form-item>

        <el-form-item label="事件类型">
          <el-select v-model="militaryEvent.eventType" placeholder="请选择类型">
            <el-option label="战斗" value="战斗" />
            <el-option label="演习" value="演习" />
            <el-option label="部署" value="部署" />
            <el-option label="侦察" value="侦察" />
          </el-select>
        </el-form-item>

        <el-form-item label="发生时间">
          <el-date-picker
            v-model="militaryEvent.occurrenceTime"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>

        <el-form-item label="上报时间">
          <el-date-picker
            v-model="militaryEvent.reportTime"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>

        <el-form-item label="地点描述">
          <el-input v-model="militaryEvent.locationDescription" />
        </el-form-item>

        <el-form-item label="坐标">
          <el-input v-model="militaryEvent.longitude" style="width: 180px" />
          <el-input v-model="militaryEvent.latitude" style="width: 180px; margin-left: 10px" />
        </el-form-item>

        <el-form-item label="上报人">
          <el-input v-model="militaryEvent.reporter" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEvent">提交</el-button>
      </template>
    </el-dialog>

    <!-- 控件容器 -->
    <div id="controlContainer">
      <!-- 搜索功能 -->
      <div class="control-group">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入地名进行搜索"
          @keyup.enter="search"
          style="width: 220px"
        />
        <el-button type="primary" @click="search" style="margin-left: 5px">
          搜索
        </el-button>
      </div>

      <!-- 图层切换 -->
      <div class="control-group">
        <span>图层：</span>
        <el-radio-group v-model="currentLayer" @change="switchLayer">
          <el-radio label="vector">矢量图</el-radio>
          <el-radio label="image">影像图</el-radio>
        </el-radio-group>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox  } from "element-plus";
const tk = import.meta.env.VITE_TDT_KEY;

const searchKeyword = ref("北京市海淀区莲花池西路28号");
const currentLayer = ref("vector");

let map = null;
let zoom = 12;
let geocoder = null;
let currentMarker = null;
let vectorLayer = null;
let imageLayer = null;

const dialogVisible = ref(false);
// 军事事件对象
const militaryEvent = ref({
  id: null,
  eventName: "",
  eventDescription: "",
  eventType: "",
  occurrenceTime: null,
  reportTime: new Date(), // 默认是当前时间
  locationDescription: "",
  latitude: null,
  longitude: null,
  reporter: "",
});

// 初始化地图
function initializeMap() {
  // 矢量图层
  const vectorURL =
    "http://t0.tianditu.gov.cn/vec_w/wmts?" +
    "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
    "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=" +
    tk;
  // 影像图层
  const imageURL =
    "http://t0.tianditu.gov.cn/img_w/wmts?" +
    "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
    "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=" +
    tk;

  vectorLayer = new T.TileLayer(vectorURL, { minZoom: 1, maxZoom: 18 });
  imageLayer = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 });

  map = new T.Map("mapDiv", { layers: [vectorLayer] });
  map.centerAndZoom(new T.LngLat(116.40969, 39.89945), zoom);
  map.enableScrollWheelZoom();

  geocoder = new T.Geocoder();

  // 右键菜单
  const menu = new T.ContextMenu({ width: 160 });
  const menuItem = new T.MenuItem("填写军事事件", (lnglat) => {
    militaryEvent.value.longitude = lnglat.getLng();
    militaryEvent.value.latitude = lnglat.getLat();
    dialogVisible.value = true;
  });
  menu.addItem(menuItem);
  map.addContextMenu(menu);
}

// 提交事件
async function submitEvent() {
  try {
    console.log("提交的军事事件数据:", militaryEvent.value);

    const res = await axios.post("/api/map/report", militaryEvent.value);

    if (res.data.code !== 0) {
      ElMessage.error(res.data.message || "提交军事事件失败！");
      return;
    }

    ElMessage.success("军事事件已提交！");
    dialogVisible.value = false;
  } catch (err) {
    ElMessage.error("提交军事事件失败！");
  }
}
// 搜索
function search() {
  if (!searchKeyword.value) {
    ElMessage.warning("请输入要搜索的地名");
    return;
  }
  map.clearOverLays();
  currentMarker = null;

  geocoder.getPoint(searchKeyword.value, (result) => {
    if (result.getStatus() === 0) {
      if (currentMarker) {
        map.removeOverLay(currentMarker);
      }
      map.panTo(result.getLocationPoint(), 16);
      currentMarker = new T.Marker(result.getLocationPoint());
      map.addOverLay(currentMarker);
    } else {
      ElMessage.error(result.getMsg() || "未找到相关地点");
    }
  });
}

// 切换图层
function switchLayer() {
  if (!map) return;
  if (currentLayer.value === "vector") {
    map.removeLayer(imageLayer);
    map.addLayer(vectorLayer);
  } else {
    map.removeLayer(vectorLayer);
    map.addLayer(imageLayer);
  }
}

function getVisibleRegion() {
  if (!map) return null;

  const bounds = map.getBounds();           // 获取可视区域
  const sw = bounds.getSouthWest();         // 左下角
  const ne = bounds.getNorthEast();         // 右上角

  return {
    minLatitude: sw.getLat(),
    maxLatitude: ne.getLat(),
    minLongitude: sw.getLng(),
    maxLongitude: ne.getLng()
  };
}

// 用于存储当前标注，方便刷新时清除
let eventMarkers = [];
async function fetchEventsInView() {
  const region = getVisibleRegion();
  if (!region) return;

  try {
    const res = await axios.post("/api/map/events", region);
    if (res.data.code === 0) {
      const events = res.data.data; // 注意这里是 data

      if (!Array.isArray(events)) {
        console.error("后台返回事件不是数组:", events);
        return;
      }

      // 清除旧标注
      eventMarkers.forEach(marker => map.removeOverLay(marker));
      eventMarkers = [];

      // 添加新标注
      events.forEach(event => {
        const icon = new T.Icon({
          iconUrl: "sword.png",
          iconSize: new T.Point(27, 27),
          iconAnchor: new T.Point(10, 25)
        });

        const marker = new T.Marker(new T.LngLat(event.longitude, event.latitude), { icon });
        map.addOverLay(marker);
        eventMarkers.push(marker);

        // 点击显示详情
        marker.addEventListener("click", () => {
          const content = `
            事件名称: ${event.eventName}<br>
            类型: ${event.eventType}<br>
            时间: ${event.occurrenceTime}<br>
            描述: ${event.eventDescription}<br>
            上报人: ${event.reporter}
          `;
          ElMessageBox.alert(content, "事件详情", { confirmButtonText: "关闭" });
        });
      });

    } else {
      console.error("获取事件失败:", res.data.message);
    }
  } catch (err) {
    console.error("请求异常:", err);
  }
}

onMounted(async () => {
  try {
    // 假设后端接口提供 tk
    initializeMap(tk);
    fetchEventsInView();
    map.addEventListener("moveend", () => {
      fetchEventsInView(); // 拿到当前可视区域范围去查询事件
    });
  } catch (err) {
    console.error("地图加载失败", err);
  }
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%; /* 占满整个可视高度 */
  position: absolute;
  padding: 0;
}
.map {
  width: 100%;
  height: 100%;
}
#controlContainer {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  background: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}
.control-group {
  margin-bottom: 10px;
}
</style>
